<?php

namespace app\index\controller;

use tencentLive\tencentapi;
use think\Controller;
use think\Db;
use think\Log;
use think\Request;

class Live extends Controller
{
    /**
     * 检测版本更新
     * api POST /index/{controller}/{method}
     * @param string version  *版本号
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return string data 新版本下载地址
     * */
    public function checkVersion()
    {
        $input = Request()->param();

        $version = $input['version'];

        if (empty($version)) apiReturn(2, '版本号信息缺失');

        if ($version >= C('VERSION')) {
            apiReturn(1, '当前是最新版本');
        } else {
            apiReturn(1, '检测到新版本', C('VERSION_URL'));
        }
    }

    /**
     * 登录
     * api POST /index/{controller}/{method}
     * @param string mobile  *账号
     * @param string password *密码
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data.id 用户id
     * @return string data.mobile 手机号
     */
    public function login()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入账号');
        if (empty($password)) apiReturn(2, '请输入密码');

        $info = Db::name('user')->field('id,mobile,password')->where(['mobile' => $mobile])->find();
        if ($info) {
            if ($info['password'] !== thinkEncrypt($password)) {
                apiReturn(2, '密码错误');
            } else {
                $info['mobile'] = hideMobile($info['mobile']);

                unset($info['password']);

                apiReturn(1, '获取数据成功', $info);
            }
        } else {
            apiReturn(2, '账号不存在或已删除');
        }
    }

    /**
     * 短信发送
     * api POST /index/{controller}/{method}
     * @param string mobile   *账号
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function sendSms()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];

        //获取手机号
        $pattern = "/^1[0123456789]\d{9}$/";
        if (empty($mobile)) {
            apiReturn(2, '请输入手机号');
        } else {
            if (preg_match($pattern, $mobile)) {
                $result = Db::name('sms_code')->where(['mobile' => $mobile])->order('create_time desc')->find();
                $result = time() - $result['create_time'];
                if ($result < 60 and $result > 0) apiReturn(2, '当前手机号操作频繁,请60秒后发送');

                $code = rand(1000, 9999);
                $statusStr = [
                    "0" => 1,
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                ];
                $smsApi = "http://api.smsbao.com/";
                $user = C('SMS_ACC');
                $pass = md5(C('SMS_PWD'));
                $content = "【乐驰车联】尊敬的用户您的验证码" . $code . "如非本人操作，请忽略。";
                $sendUrl = $smsApi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $mobile . "&c=" . urlencode($content);
                $result = file_get_contents($sendUrl);
                if ($result == 0) {
                    $data = [
                        'code' => $code,
                        'mobile' => $mobile,
                        'create_time' => time(),
                        'failure_time' => time() + 600
                    ];

                    Db::name('sms_code')->insert($data);
                    apiReturn(1, '短信发送成功');
                } else {
                    apiReturn(2, $statusStr[$result]);
                }
            } else {
                apiReturn(2, '手机号码格式错误');
            }
        }
    }

    /**
     * 忘记密码
     * api POST /index/{controller}/{method}
     * @param string mobile   *账号
     * @param string code   *验证码
     * @param string password   *密码
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function forgetPassword()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $code = $input['code'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入账号');
        if (empty($code)) apiReturn(2, '请输入验证码');
        if (empty($password)) apiReturn(2, '请输入密码');

        $info = Db::name('user')->where(['mobile' => $mobile])->find();
        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '账号已被禁用');

            $sms_info = Db::name('sms_code')->where(['mobile' => $mobile])->order('id desc')->find();

            if (empty($sms_info) || $sms_info['is_failure'] == 1 || $sms_info['failure_time'] < time() || $sms_info['code'] != $code) apiReturn(2, '验证码错误');

            $data = [
                'password' => thinkEncrypt($password),
                'update_time' => time()
            ];

            $res = Db::name('user')->where(['mobile' => $mobile])->update($data);
            if ($res) {
                Db::name('sms_code')->where(['id' => $sms_info['id']])->setField('is_failure', 1);

                apiReturn(1, '重置密码成功');
            } else {
                apiReturn(2, '重置密码失败');
            }
        } else {
            apiReturn(2, '账号不存在或已删除');
        }
    }

    /**
     * 修改密码
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param string password   *原密码
     * @param string new_password   *新密码
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function editPassword()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $password = $input['password'];
        $new_password = $input['new_password'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($password)) apiReturn(2, '请输入原密码');
        if (empty($new_password)) apiReturn(2, '请输入新密码');
        if ($password == $new_password) apiReturn(2, '原密码不可与新密码一致');
        if (strlen($new_password) < 6) apiReturn(2, '新密码长度至少6位');

        $info = Db::name('user')->where(['id' => $user_id])->find();
        if ($info) {
            if (thinkEncrypt($password) !== $info['password']) apiReturn(2, '原密码错误');

            $res = Db::name('user')->where(['id' => $user_id])->setField('password', thinkEncrypt($new_password));
            if ($res) {
                apiReturn(1, '修改密码成功');
            } else {
                apiReturn(2, '修改密码失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }


    }

    /**
     * 首页数据统计
     * api POST /index/{controller}/{method}
     * @param int user_id *用户id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data.virtualman_count 形象启用 / 形象可选
     * @return string data.sum_use_video_time 已用时长
     * @return string data.surplus_video_time 剩余时长
     * @return int data.live_count 已有直播间
     * @return int data.use_live_count 使用中直播间
     * @return int data.goods_copywrite_tag_count 已有文案主题
     * @return string data.all_time 已有文案总时长
     * */
    public function indexCensus()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '用户id缺失');

        // 形象启用、可选：虚拟人数量
        // 已用时长：文案视频总时长；剩余时长：后台配置总时长-已用时长
        // 已有直播间：创建的直播间；使用中：开播过的直播间
        // 已有文案主题：商品文案标签；总时长：商品文案视频时长+商品文案问答视频时长+互动文案视频时长

        // 形象启用 / 形象可选
        $virtualman_count = Db::name('virtualman')->count();

        // 商品文案视频总时长（秒）
        $goods_copywrite_sum_video_time = Db::name('goods_copywrite_tag t')->join('ai_goods_copywrite c', 't.id = c.tag_id')->where(['t.user_id' => $user_id, 't.is_del' => 0])->sum('c.video_time');
        // 互动文案视频总时长（秒）
        $interact_copywrite_sum_video_time = Db::name('interact_copywrite')->where(['user_id' => $user_id])->sum('video_time');

        // 已用时长 / 总时长 = 商品文案视频总时长 + 互动文案视频总时长
        $sum_use_video_time = $goods_copywrite_sum_video_time + $interact_copywrite_sum_video_time;
        // 剩余时长
        $surplus_video_time = C('USER_ALL_VIDEO_TIME') > $sum_use_video_time ? C('USER_ALL_VIDEO_TIME') * 60 - $sum_use_video_time : 0;

        // 已有直播间
        $live_count = Db::name('live')->where(['user_id' => $user_id])->count();
        // 使用中直播间
        $use_live_count = 0;

        // 已有文案主题
        $goods_copywrite_tag_count = Db::name('goods_copywrite_tag')->where(['user_id' => $user_id, 'is_del' => 0])->count();

        $data = [
            'virtualman_count' => $virtualman_count,
            'sum_use_video_time' => formatTime($sum_use_video_time),
            'surplus_video_time' => formatTime($surplus_video_time),
            'live_count' => $live_count,
            'use_live_count' => $use_live_count,
            'goods_copywrite_tag_count' => $goods_copywrite_tag_count,
            'all_time' => formatTime($sum_use_video_time),
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 虚拟人列表
     * api POST /index/{controller}/{method}
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return string list.virtualman_key 虚拟人key
     * @return string list.name 名称
     * @return string list.pose_image 姿态图片url
     * @return string list.type 类型；1：竖屏，2：横屏
     * @return array list.timbre_list 虚拟人音色列表
     * @return string timbre_list.timbre_key 音色key
     * @return string timbre_list.timbre_name 音色名称
     * @return string timbre_list.timbre_sample 音色url
     * */
    public function virtualmanList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('virtualman_figure')->field('virtualman_key,name,pose_image,type')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $timbre_list = Db::name('virtualman_timbre')->field('timbre_key,timbre_name,timbre_sample')->where(['virtualman_key' => $v['virtualman_key']])->select();
                $v['timbre_list'] = $timbre_list ? : [];
            }
        } else {
            $list = [];
        }

        $count = Db::name('virtualman')->count();
        $total_page = $count ? ceil($count / $pagesize) : 0;

        listApiReturn(1, '获取数据成功', $list, $total_page);
    }

    /**
     * 前景列表
     * api POST /index/{controller}/{method}
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return int list.id 图片id
     * @return string list.img 图片url
     * */
    public function frontImgList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('front_img')->field('id,img')->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
        } else {
            $list = [];
        }

        $count = Db::name('front_img')->count();
        $total_page = $count ? ceil($count / $pagesize) : 0;

        listApiReturn(1, '获取数据成功', $list, $total_page);
    }

    /**
     * 背景列表
     * api POST /index/{controller}/{method}
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return int list.id 图片id
     * @return string list.img 图片url
     * */
    public function behindImgList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('behind_img')->field('id,img')->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
        } else {
            $list = [];
        }

        $count = Db::name('behind_img')->count();
        $total_page = $count ? ceil($count / $pagesize) : 0;

        listApiReturn(1, '获取数据成功', $list, $total_page);
    }

    /**
     * 设置模板
     * api POST /index/{controller}/{method}
     * @param int user_id *用户id
     * @param string fodder_data   *素材信息（资源，位置，尺寸信息），json字符串，当客户端需要的时候，原样返回
     * @param int live_id   直播间id
     * @param int id   模板id，点击【设为模板】时，请勿传递该参数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data 模板id
     * */
    public function saveTemplate()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $user_id = $input['user_id'];
        $fodder_data = $input['fodder_data'];
        $live_id = $input['live_id'] ? : 0;

        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        if (empty($fodder_data)) apiReturn(2, '素材信息缺失');

        $time = time();

        $data = [
            'user_id' => $user_id,
            'fodder_data' => $fodder_data,
        ];

        if ($live_id) $data['live_id'] = $live_id;

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('template')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $data['create_time'] = $time;

            $id = Db::name('template')->insertGetId($data);
            if ($id) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        }
    }

    /**
     * 模板列表
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return int list.id 模板id
     * @return int list.live_id 直播间id
     * @return string list.fodder_data 素材信息（资源，位置，尺寸信息）
     * */
    public function templateList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('template')->field('id,live_id,fodder_data')->where(['user_id' => $user_id, 'live_id' => 0])->order('id desc')->page($page, $pagesize)->select();

        $count = Db::name('template')->count();
        $total_page = $count ? ceil($count / $pagesize) : 0;

        listApiReturn(1, '获取数据成功', $list, $total_page);
    }

    /**
     * 删除模板
     * api POST /index/{controller}/{method}
     * @param int id   *模板id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function delTemplate()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '模板ID缺失');

        $info = Db::name('template')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('template')->where(['id' => $id])->delete();

            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 设置商品文案标签
     * api POST /index/{controller}/{method}
     * @param int user_id *用户id
     * @param string name   *文案标签
     * @param int id   文案标签id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data 商品文案标签id
     * */
    public function setGoodsCopywriteTag()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $user_id = $input['user_id'];
        $name = $input['name'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        if (empty($name)) apiReturn(2, '请输入文案标签');

        $where['user_id'] = $user_id;
        $where['name'] = $name;
        if ($id) $where['id'] = ['neq', $id];
        $count = Db::name('goods_copywrite_tag')->where($where)->count();
        if ($count) apiReturn(2, '该文案标签已存在');

        $time = time();

        $data = [
            'user_id' => $user_id,
            'name' => $name
        ];

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('goods_copywrite_tag')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $data['create_time'] = $time;

            $id = Db::name('goods_copywrite_tag')->insertGetId($data);
            if ($id) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        }
    }

    /**
     * 设置商品文案
     * api POST /index/{controller}/{method}
     * @param int tag_id   *商品文案标签ID
     * @param int type   1：文本驱动，2：语音驱动
     * @param string content   文本内容；type==1时，content必填
     * @param string voice_url   音频地址（请勿携带域名）；type==2时，voice_url必填
     * @param int style   1：商品文案，2：商品问答
     * @param string keyword   关键词；style==2时，keyword必填
     * @param int id   商品文案id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data 商品文案ID
     * */
    public function setGoodsCopywrite()
    {
        $input = Request()->param();

        $tag_id = $input['tag_id'];
        $type = $input['type'];
        $content = $input['content'];
        $voice_url = $input['voice_url'];
        $keyword = $input['keyword'];
        $style = $input['style'];
        $id = $input['id'] ? : 0;

        if (empty($tag_id)) apiReturn(2, '商品文案标签ID缺失');
        if ($type == 1 && empty($content)) apiReturn(2, '请输入文本驱动内容');
        if ($type == 2 && empty($voice_url)) apiReturn(2, '请上传音频');
        if ($style == 2 && empty($keyword)) apiReturn(2, '请设置关键词');

        $time = time();

        $data = [
            'tag_id' => $tag_id,
            'type' => $type,
            'style' => $style
        ];

        if ($type == 1) {
            $data['content'] = $content;
        } else {
            $data['voice_url'] = $voice_url;
        }

        if ($style == 2) $data['keyword'] = $keyword;

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('goods_copywrite')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $data['create_time'] = $time;

            $id = Db::name('goods_copywrite')->insertGetId($data);
            if ($id) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        }
    }

    /**
     * 商品文案标签列表
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param string name   搜索内容
     * @param string virtualman_key   虚拟人key
     * @param string timbre_key   音色key
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return int list.id 文案标签ID
     * @return string list.name 文案标签名称
     * @return array list.goods_copywrite_list 文案列表
     * @return int goods_copywrite_list.id 文案ID
     * @return int goods_copywrite_list.type 文案驱动类型；1：文本驱动，2：语音驱动
     * @return string goods_copywrite_list.content 文本驱动内容
     * @return string goods_copywrite_list.voice_url 语音驱动内容
     * @return string goods_copywrite_list.video_url 视频url
     * @return int goods_copywrite_list.style 文案类型；1：商品文案，2：商品问答
     * @return string goods_copywrite_list.keyword 商品问答关键词
     * @return array other_data.all_ids 全部文案id集合，操作排序时请对该数据id进行对应位置调整
     * */
    public function goodsCopywriteTagList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $name = $input['name'] ? : '';
        $virtualman_key = $input['virtualman_key'] ? : '';
        $timbre_key = $input['timbre_key'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        $where['copy_id'] = 0;
        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($virtualman_key) $where['virtualman_key'] = $virtualman_key;
        if ($timbre_key) $where['timbre_key'] = $timbre_key;

        $list = Db::name('goods_copywrite_tag')->field('id,name')->where($where)->order('sort asc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $goods_copywrite_list = Db::name('goods_copywrite')->field('id,type,content,voice_url,video_url,style,keyword')->where(['tag_id' => $v['id'], 'is_del' => 0])->order('sort asc')->select();
                $v['goods_copywrite_list'] = $goods_copywrite_list ? : [];
            }
        } else {
            $list = [];
        }

        $all_list = Db::name('goods_copywrite_tag')->field('id')->where(['user_id' => $user_id])->order('sort asc')->select();
        if ($all_list) {
            $total_page = count($all_list) ? ceil(count($all_list) / $pagesize) : 0;
            $all_ids = array_column($all_list, 'id');
        } else {
            $total_page = 0;
            $all_ids = [];
        }

        listApiReturn(1, '获取数据成功', $list, $total_page, $all_ids);
    }

    /**
     * 删除商品文案标签
     * api POST /index/{controller}/{method}
     * @param int id   *商品文案标签id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function delGoodsCopywriteTag()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '商品文案标签ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('goods_copywrite_tag')->where(['id' => $id])->find();
            if ($info) {
                Db::name('goods_copywrite_tag')->where(['id' => $id])->setField('is_del', 1);
                Db::name('goods_copywrite')->where(['tag_id' => $id])->setField('is_del', 1);

                Db::commit();
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '删除失败');
        }
    }

    /**
     * 删除商品文案
     * api POST /index/{controller}/{method}
     * @param int id   *商品文案id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function delGoodsCopywrite()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '商品文案ID缺失');

        $info = Db::name('goods_copywrite')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('goods_copywrite')->where(['id' => $id])->delete();

            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 设置互动文案
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param string keyword   *关键词
     * @param int type   1：文本驱动，2：语音驱动
     * @param string content   文本内容；type==1时，content必填
     * @param string voice_url   音频地址（请勿携带域名）；type==2时，voice_url必填
     * @param int id   商品文案id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data 互动文案id
     * */
    public function setInteractCopywrite()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $keyword = $input['keyword'];
        $type = $input['type'];
        $content = $input['content'];
        $voice_url = $input['voice_url'];
        $id = $input['id'] ? : 0;

        if (empty($user_id)) apiReturn(2, '用户id缺失');
        if ($type == 1 && empty($content)) apiReturn(2, '请输入文本驱动内容');
        if ($type == 2 && empty($voice_url)) apiReturn(2, '请上传音频');

        $time = time();

        $data = [
            'user_id' => $user_id,
            'type' => $type,
            'keyword' => $keyword
        ];

        if ($type == 1) {
            $data['content'] = $content;
        } else {
            $data['voice_url'] = $voice_url;
        }

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('interact_copywrite')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $data['create_time'] = $time;

            $id = Db::name('interact_copywrite')->insertGetId($data);
            if ($id) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        }
    }

    /**
     * 互动文案列表
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param string keyword   搜索关键词
     * @param string virtualman_key   虚拟人key
     * @param string timbre_key   音色key
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return string list.keyword 商品问答关键词
     * @return int list.type 文案驱动类型；1：文本驱动，2：语音驱动
     * @return string list.content 文本驱动内容
     * @return string list.voice_url 语音驱动内容
     * @return string list.video_url 视频url
     * @return array other_data.all_ids 全部文案id集合，操作排序时请对该数据id进行对应位置调整
     * */
    public function interactCopywriteList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $keyword = $input['keyword'];
        $virtualman_key = $input['virtualman_key'] ? : '';
        $timbre_key = $input['timbre_key'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        $where['copy_id'] = 0;
        if ($keyword) $where['keyword'] = ['LIKE', '%' . $keyword . '%'];
        if ($virtualman_key) $where['virtualman_key'] = $virtualman_key;
        if ($timbre_key) $where['timbre_key'] = $timbre_key;

        $list = Db::name('interact_copywrite')->field('id,keyword,type,content,voice_url,video_url')->where($where)->order('sort asc')->page($page, $pagesize)->select();

        $all_list = Db::name('interact_copywrite')->field('id')->order('sort asc')->select();
        if ($all_list) {
            $total_page = ceil(count($all_list) / $pagesize);
            $all_ids = array_column($all_list, 'id');
        } else {
            $total_page = 0;
            $all_ids = [];
        }

        listApiReturn(1, '获取数据成功', $list, $total_page, $all_ids);
    }

    /**
     * 删除互动文案
     * api POST /index/{controller}/{method}
     * @param int id   *互动文案id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function delInteractCopywrite()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '互动文案ID缺失');

        $info = Db::name('interact_copywrite')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('interact_copywrite')->where(['id' => $id])->setField('is_del', 1);

            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文案排序
     * api POST /index/{controller}/{method}
     * @param string sort_ids 排序id集合
     * @param string type 排序类型，1：商品文案标签排序，2：商品文案排序，3：互动文案排序
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function copywriteSort()
    {
        $input = Request()->param();

        $sort_ids = $input['sort_ids'];
        $type = $input['type'];

        if (empty($sort_ids)) apiReturn(2, '排序数据缺失');
        if (empty($type)) apiReturn(2, '排序类型缺失');

        switch ($type) {
            case 1:
                $db = 'goods_copywrite_tag';
                break;
            case 2:
                $db = 'goods_copywrite';
                break;
            case 3:
                $db = 'interact_copywrite';
        }

        Db::startTrans();
        try {
            $sort_ids_arr = explode(',', $sort_ids);

            $data = [
                'sort' => 0,
                'update_time' => time()
            ];
            Db::name($db)->where(['id' => ['IN', $sort_ids_arr]])->update($data);
            if ($sort_ids_arr) {
                foreach ($sort_ids_arr as $k => $v) {
                    Db::name($db)->where(['id' => $v])->setField('sort', $k + 1);
                }
            }
            Db::commit();
            apiReturn(1, '更新排序成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '更新排序失败', $e);
        }
    }

    /**
     * 保存直播间
     * api POST /index/{controller}/{method}
     * @param int user_id   *用户id
     * @param string name   *直播间名称
     * @param string virtualman_key   *虚拟人key
     * @param string virtualman_name   *虚拟人名称
     * @param string virtualman_pose_image   *虚拟人姿态图片
     * @param string timbre_key   *音色key
     * @param string timbre_sample   *音色地址
     * @param int cover_id   直播间封面图id
     * @param string goods_copywrite_json   商品文案数据；示例：[{"tag_id":1,"goods_copywrite_ids":"1,2"},{"tag_id":2,"goods_copywrite_ids":"3,4"}]
     * @param string interact_copywrite_ids   互动文案id集合数据，英文逗号分隔
     * @param int id   直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data 直播间id
     * */
    public function saveLiveRoom()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $name = $input['name'];
        $cover_id = $input['cover_id'];
        $virtualman_key = $input['virtualman_key'];
        $virtualman_name = $input['virtualman_name'];
        $virtualman_pose_image = $input['virtualman_pose_image'];
        $timbre_key = $input['timbre_key'];
        $timbre_sample = $input['timbre_sample'];
        $goods_copywrite_json = $input['goods_copywrite_json'] ? : '';
        $interact_copywrite_ids = $input['interact_copywrite_ids'] ? : '';
        $id = $input['id'] ? : 0;

        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        if (empty($name)) apiReturn(2, '请设置直播间名称');
        //        if (empty($cover_id)) apiReturn(2, '直播间封面图缺失');
        if (empty($virtualman_key)) apiReturn(2, '虚拟人key缺失');
        if (empty($virtualman_name)) apiReturn(2, '虚拟人名称缺失');
        if (empty($virtualman_pose_image)) apiReturn(2, '虚拟人姿态图片缺失');
        if (empty($timbre_key)) apiReturn(2, '音色key缺失');
        if (empty($timbre_sample)) apiReturn(2, '音色地址缺失');

        $time = time();

        $data = [
            'user_id' => $user_id,
            'name' => $name,
            'cover_id' => $cover_id,
            'virtualman_key' => $virtualman_key,
            'virtualman_name' => $virtualman_name,
            'virtualman_pose_image' => $virtualman_pose_image,
            'timbre_key' => $timbre_key,
            'timbre_sample' => $timbre_sample,
            'goods_copywrite_json' => $goods_copywrite_json,
            'interact_copywrite_ids' => $interact_copywrite_ids
        ];

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('live')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $data['create_time'] = $time;

            $id = Db::name('live')->insertGetId($data);
            if ($id) {
                apiReturn(1, '保存成功', intval($id));
            } else {
                apiReturn(2, '保存失败');
            }
        }
    }

    /**
     * 直播间列表
     * api POST /index/{controller}/{method}
     * @param int user_id *用户id
     * @param int page   当前页数
     * @param int pagesize   每页条数
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int total_page 总页数
     * @return int list.id 直播间id
     * @return string list.cover 直播间封面图
     * @return string list.name 直播间名称
     * */
    public function liveRoomList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '用户ID缺失');

        $list = Db::name('live')->field('id,cover_id cover,name')->where(['user_id' => $user_id, 'is_del' => 0])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['cover'] = getPicture($v['cover']);
            }
        } else {
            $list = [];
        }

        $count = Db::name('live')->where(['user_id' => $user_id, 'is_del' => 0])->count();
        $total_page = $count ? ceil($count / $pagesize) : 0;

        listApiReturn(1, '获取数据成功', $list, $total_page);
    }

    /**
     * 删除直播间
     * api POST /index/{controller}/{method}
     * @param int id *直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function delLiveRoom()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '直播间ID缺失');

        $info = Db::name('live')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            $res = Db::name('live')->where(['id' => $id])->update(['is_del' => 1, 'update_time' => time()]);
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '直播间不存在或已删除');
        }
    }

    /**
     * 直播间信息
     * api POST /index/{controller}/{method}
     * @param int id   *直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int id   直播间id
     * @return string data.name   直播间名称
     * @return int data.cover_id   直播间封面图id
     * @return string data.cover_path   直播间封面图地址
     * @return string data.virtualman_key   虚拟人key
     * @return string data.virtualman_name   虚拟人名称
     * @return string data.virtualman_pose_image   虚拟人姿态图片
     * @return string data.timbre_key   音色key
     * @return string data.timbre_sample   音色地址
     * @return string data.goods_copywrite_json   商品文案数据
     * @return array data.goods_copywrite_json_list   商品文案数据（详细数据）
     * @return int goods_copywrite_json_list.id 文案标签id
     * @return int goods_copywrite_json_list.name 文案标签名称
     * @return array goods_copywrite_json_list.goods_copywrite_list 文案列表数据
     * @return int goods_copywrite_list.id 文案id
     * @return int goods_copywrite_list.type  文案驱动类型；1：文本驱动，2：语音驱动
     * @return string goods_copywrite_list.content  文本驱动内容
     * @return string goods_copywrite_list.voice_url 语音驱动内容
     * @return int goods_copywrite_list.style 文案类型；1：商品文案，2：商品问答
     * @return string goods_copywrite_list.keyword 商品问答关键词
     * @return int goods_copywrite_list.video_time 时长（秒）
     * @return string goods_copywrite_list.video_url 播放链接
     * @return int goods_copywrite_list.video_status 是否生成视频；0：未生成，1：已生成
     * @return string goods_copywrite_list.video_time_text 格式化时长
     * @return string data.interact_copywrite_ids   互动文案id集合数据
     * @return array data.interact_copywrite_list   互动文案数据（详细数据）
     * @return int interact_copywrite_list.id 互动文案id
     * @return string interact_copywrite_list.keyword 商品问答关键词
     * @return int interact_copywrite_list.type 文案驱动类型；1：文本驱动，2：语音驱动
     * @return string interact_copywrite_list.content 文本驱动内容
     * @return string interact_copywrite_list.voice_url 语音驱动内容
     * @return string interact_copywrite_list.virtualman_key 虚拟人key
     * @return string interact_copywrite_list.timbre_key 音色key
     * @return int interact_copywrite_list.video_time 时长（秒）
     * @return string interact_copywrite_list.video_url 播放链接
     * @return int interact_copywrite_list.video_status 是否生成视频；0：未生成，1：已生成
     * @return string interact_copywrite_list.video_time_text 格式化时长
     * @return int template_info.id 模板id
     * @return string template_info.fodder_data 素材信息（资源，位置，尺寸信息）
     * */
    public function liveRoomInfo()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '直播间id缺失');

        $info = Db::name('live')->field('id,name,cover_id,virtualman_key,virtualman_name,virtualman_pose_image,timbre_key,timbre_sample,goods_copywrite_json,interact_copywrite_ids')->where(['id' => $id])->find();
        if ($info) {
            $info['cover_path'] = getPicture($info['cover_id']);

            $goods_copywrite_json = json_decode($info['goods_copywrite_json'], true);
            $goods_copywrite_json_list = [];
            if ($goods_copywrite_json) {
                foreach ($goods_copywrite_json as $k => $v) {
                    $goods_copywrite_tag_info = Db::name('goods_copywrite_tag')->field('id,name,virtualman_key,timbre_key')->where(['id' => $v['tag_id']])->find();
                    $goods_copywrite_json_list[$k]['id'] = $goods_copywrite_tag_info['id'];
                    $goods_copywrite_json_list[$k]['name'] = $goods_copywrite_tag_info['name'];
                    if ($v['goods_copywrite_ids']) {
                        $sql = "SELECT `id`,`type`,`content`,`voice_url`,`style`,`keyword`,`video_time`,`video_url`,`video_status` FROM `ai_goods_copywrite` WHERE `id` IN (" . $v['goods_copywrite_ids'] . ") ORDER BY FIELD(`id`, " . $v['goods_copywrite_ids'] . ")";
                        $search_goods_copywrite_list = Db::query($sql);
                        if ($search_goods_copywrite_list) {
                            foreach ($search_goods_copywrite_list as &$value) {
                                $value['video_time'] = intval($value['video_time']);
                                $value['video_time_text'] = formatVideoTime($value['video_time']);
                            }
                        }
                        $goods_copywrite_json_list[$k]['goods_copywrite_list'] = $search_goods_copywrite_list ? : [];
                    } else {
                        $goods_copywrite_json_list[$k]['goods_copywrite_list'] = [];
                    }
                }
            }
            $info['goods_copywrite_json_list'] = $goods_copywrite_json_list;

            $interact_copywrite_ids = $info['interact_copywrite_ids'];
            if ($interact_copywrite_ids) {
                $interact_copywrite_list = Db::name('interact_copywrite')->field('id,keyword,type,content,voice_url,virtualman_key,timbre_key,video_time,video_url,video_status')->where(['id' => ['IN', $interact_copywrite_ids]])->order('sort asc')->select();
                if ($interact_copywrite_list) {
                    foreach ($interact_copywrite_list as &$value) {
                        $value['video_time'] = intval($value['video_time']);
                        $value['video_time_text'] = formatVideoTime($value['video_time']);
                    }
                }
            }
            $info['interact_copywrite_list'] = $interact_copywrite_list ? : [];

            $template_info = Db::name('template')->field('id,fodder_data')->where(['live_id' => $id])->find();
            $info['template_info'] = $template_info ? : [];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '直播间不存在或已删除');
        }
    }

    /**
     * 试听
     * api POST /index/{controller}/{method}
     * @param int id   *文案id
     * @param int type   *文案类型；1：商品文案，2：互动文案
     * @param string virtualman_key   *虚拟人key
     * @param string timbre_key   *音色key
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return string data   音频url
     * */
    public function listen()
    {
        $input = Request()->param();

        $id = $input['id'];                        // 文案id
        $type = $input['type'];                    // 1：商品文案，2：互动文案
        $virtualman_key = $input['virtualman_key'];// 虚拟人key
        $timbre_key = $input['timbre_key'];        // 音色key

        if (empty($id)) apiReturn(2, '文案id缺失');
        if (empty($type)) apiReturn(2, '文案类型缺失');


        $db_name = $type == 1 ? 'goods_copywrite' : 'interact_copywrite';

        $info = Db::name($db_name)->where(['id' => $id])->find();
        if ($info) {
            if ($info['audio_status'] == 0) {
                // 生成音频
                if ($info['audio_code']) {
                    $result = (new tencentapi())->getProgress($info['audio_code']);
                    $result = json_decode($result, true);
                    if ($result['Header']['Code'] == 0 && $result['Payload']['Progress'] == 100 && $result['Payload']['MediaUrl']) {
                        // 音频生成完毕
                        $data = [
                            'audio_url' => $result['Payload']['MediaUrl'],
                            'audio_status' => 1,
                            'update_time' => time()
                        ];
                        Db::name($db_name)->where(['id' => $id])->update($data);
                        apiReturn(1, '获取数据成功', $info['audio_url']);
                    } else {
                        apiReturn(2, '音频正在生成中，请稍后进行试听');
                    }
                } else {
                    $result = (new tencentapi())->tts($virtualman_key, $timbre_key, $info['content']);
                    $result = json_decode($result, true);
                    if ($result['Header']['Code'] == 0) {
                        $audio_code = $result['Payload']['TaskId'];
                        $data = [
                            'audio_code' => $audio_code,
                            'update_time' => time()
                        ];
                        Db::name($db_name)->where(['id' => $id])->update($data);

                        apiReturn(2, '音频正在生成中，请稍后进行试听');
                    }
                }
            } else {
                apiReturn(1, '获取数据成功', $info['audio_url']);
            }
        } else {
            apiReturn(2, '文案不存在或已删除');
        }
    }

    /**
     * 开启直播=>已选文案绑定虚拟人和音色（1：保存直播间，2：已选文案绑定虚拟人和音色）
     * api POST /index/{controller}/{method}
     * @param int id   *直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function openLiveBindKey()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '直播间id缺失');

        $info = Db::name('live')->where(['id' => $id])->find();
        if ($info) {
            if ($info['virtualman_key'] && $info['timbre_key']) {
                Db::startTrans();
                try {
                    $goods_copywrite_json = json_decode($info['goods_copywrite_json'], true);
                    $tag_id_arr = array_column($goods_copywrite_json, 'tag_id');

                    $data = [
                        'virtualman_key' => $info['virtualman_key'],
                        'timbre_key' => $info['timbre_key'],
                        'update_time' => time()
                    ];

                    if ($tag_id_arr) {
                        foreach ($tag_id_arr as $v) {
                            $tag_info = Db::name('goods_copywrite_tag')->where(['id' => $v])->find();
                            // 商品文案标签未绑定数字人和音色 key
                            if (!$tag_info['virtualman_key'] || !$tag_info['timbre_key']) {
                                Db::name('goods_copywrite_tag')->where(['id' => ['IN', $v]])->update($data);
                            } else {
                                // 文案选重复，需要复制文案出来，重新绑定数字人和音色 key
                                if ($tag_info['virtualman_key'] != $info['virtualman_key'] || $tag_info['timbre_key'] != $info['timbre_key']) {
                                    $copy_tag_data = [
                                        'user_id' => $info['user_id'],
                                        'name' => $tag_info['name'],
                                        'virtualman_key' => $info['virtualman_key'],
                                        'timbre_key' => $info['timbre_key'],
                                        'create_time' => time(),
                                        'copy_id' => $v
                                    ];
                                    $new_id = Db::name('goods_copywrite_tag')->insertGetId($copy_tag_data);
                                    copyGoodsCopywrite($v, $new_id, $id);
                                }
                            }
                        }
                    }

                    $interact_copywrite_ids_arr = explode(',', $info['interact_copywrite_ids']);

                    if ($interact_copywrite_ids_arr) {
                        $new_interact_copywrite_arr = [];
                        foreach ($interact_copywrite_ids_arr as &$v) {
                            $interact_copywrite_info = Db::name('interact_copywrite')->where(['id' => $v])->find();
                            // 互动文案标签未绑定数字人和音色 key
                            if (!$interact_copywrite_info['virtualman_key'] || !$interact_copywrite_info['timbre_key']) {
                                Db::name('interact_copywrite')->where(['id' => $v])->update($data);

                                $new_interact_copywrite_arr[] = $v;
                            } else {
                                // 文案选重复，需要复制文案出来，重新绑定数字人和音色 key
                                if ($interact_copywrite_info['virtualman_key'] != $info['virtualman_key'] || $interact_copywrite_info['timbre_key'] != $info['timbre_key']) {
                                    $copy_data = [
                                        'user_id' => $info['user_id'],
                                        'keyword' => $interact_copywrite_info['keyword'],
                                        'type' => $interact_copywrite_info['type'],
                                        'content' => $interact_copywrite_info['content'],
                                        'voice_url' => $interact_copywrite_info['voice_url'],
                                        'virtualman_key' => $info['virtualman_key'],
                                        'timbre_key' => $info['timbre_key'],
                                        'sort' => $interact_copywrite_info['sort'],
                                        'create_time' => time(),
                                        'copy_id' => $v
                                    ];
                                    $new_id = Db::name('interact_copywrite')->insertGetId($copy_data);

                                    $new_interact_copywrite_arr[] = $new_id;
                                } else {
                                    $new_interact_copywrite_arr[] = $v;
                                }
                            }
                        }

                        $return_interact_copywrite_ids = $new_interact_copywrite_arr ? implode(',', $new_interact_copywrite_arr) : '';
                        Db::name('live')->where(['id' => $id])->setField('interact_copywrite_ids', $return_interact_copywrite_ids);
                    }

                    // 合成视频
                    $this->compositionVideo($id);

                    Db::commit();
                    apiReturn(1, '开启直播成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    apiReturn(2, '开启直播失败');
                }
            }
        } else {
            apiReturn(2, '直播间不存在或已删除');
        }
    }

    /**
     * 直播间文案视频合成进度
     * api POST /index/{controller}/{method}
     * @param int live_id   *直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data.all_video_count 总视频数
     * @return int data.complete_count 合成完毕视频数
     * @return int data.will_complete_count 合成未完成视频数
     * @return array data.goods_copywrite_list 商品文案列表
     * @return int goods_copywrite_list.id 文案id
     * @return int goods_copywrite_list.tag_id 文案标签id
     * @return int goods_copywrite_list.video_time 视频时长
     * @return int goods_copywrite_list.video_time_text 格式化时长
     * @return string goods_copywrite_list.video_url 视频地址
     * @return string goods_copywrite_list.video_code 视频code
     * @return int goods_copywrite_list.video_status 视频生成状态；0：未生成，1：已生成
     * @return int goods_copywrite_list.style 1：商品文案，2：商品问答
     * @return array data.interact_copywrite_list 互动文案列表
     * @return int interact_copywrite_list.id 文案id
     * @return int interact_copywrite_list.video_time 视频时长
     * @return int interact_copywrite_list.video_time_text 格式化时长
     * @return string interact_copywrite_list.video_url 视频地址
     * @return string interact_copywrite_list.video_code 视频code
     * @return int interact_copywrite_list.video_status 视频生成状态；0：未生成，1：已生成
     * */
    public function videoCompositionProgress()
    {
        $input = Request()->param();

        $live_id = $input['live_id'];

        if (empty($live_id)) apiReturn(2, '直播间id缺失');

        $info = Db::name('live')->where(['id' => $live_id])->find();
        if ($info) {
            $goods_copywrite_arr = json_decode($info['goods_copywrite_json'], true);
            $goods_copywrite_ids_str = '';
            $goods_copywrite_tag_ids_str = '';
            if ($goods_copywrite_arr) {
                foreach ($goods_copywrite_arr as &$v) {
                    if ($v['goods_copywrite_ids']) {
                        if ($goods_copywrite_ids_str == '') {
                            $goods_copywrite_ids_str = $v['goods_copywrite_ids'];
                        } else {
                            $goods_copywrite_ids_str .= ',' . $v['goods_copywrite_ids'];
                        }

                        if ($goods_copywrite_tag_ids_str == '') {
                            $goods_copywrite_tag_ids_str = $v['tag_id'];
                        } else {
                            $goods_copywrite_tag_ids_str .= ',' . $v['tag_id'];
                        }
                    }
                }
            }

            $goods_copywrite_video_complete_count = 0;
            if ($goods_copywrite_ids_str) {
                //                $goods_copywrite_list = Db::name('goods_copywrite')->field('id,tag_id,video_time,video_url,video_code,video_status,style')->where(['id' => ['IN', $goods_copywrite_ids_str]])->select();
                $sql = " SELECT id,tag_id,video_time,video_url,video_code,video_status,style FROM `ai_goods_copywrite` WHERE `tag_id` IN (" . $goods_copywrite_tag_ids_str . ") and (`id` IN (" . $goods_copywrite_ids_str . ") || style = 2) ";
                $goods_copywrite_list = Db::name('goods_copywrite')->query($sql);
                if ($goods_copywrite_list) {
                    foreach ($goods_copywrite_list as &$v) {
                        $v['video_time_text'] = formatVideoTime($v['video_time']);
                        if ($v['video_status'] == 1) {
                            $v['progress'] = 100;

                            ++$goods_copywrite_video_complete_count;
                        } else {
                            $v['progress'] = $this->getProgress($v['video_code']);
                        }
                    }
                }
            }

            $interact_copywrite_video_complete_count = 0;
            if ($interact_copywrite_ids = $info['interact_copywrite_ids']) {
                $interact_copywrite_list = Db::name('interact_copywrite')->field('id,video_time,video_url,video_code,video_status')->where(['id' => ['IN', $interact_copywrite_ids]])->select();
                if ($interact_copywrite_list) {
                    foreach ($interact_copywrite_list as &$v) {
                        $v['video_time_text'] = formatVideoTime($v['video_time']);
                        if ($v['video_status'] == 1) {
                            $v['progress'] = 100;

                            ++$interact_copywrite_video_complete_count;
                        } else {
                            $v['progress'] = $this->getProgress($v['video_code']);
                        }
                    }
                }
            }

            $all_video_count = count($goods_copywrite_list) + count($interact_copywrite_list);
            $complete_count = $goods_copywrite_video_complete_count + $interact_copywrite_video_complete_count;
            $will_complete_count = $all_video_count - $complete_count;

            $data = [
                'all_video_count' => $all_video_count,
                'complete_count' => $complete_count,
                'will_complete_count' => $will_complete_count,
                'goods_copywrite_list' => $goods_copywrite_list,
                'interact_copywrite_list' => $interact_copywrite_list
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '直播间不存在或已删除');
        }

    }

    /**
     * 开播通知
     * api POST /index/{controller}/{method}
     * @param int item_id   *直播间id
     * @param int item_url   *直播地址
     * @param int item_type   *直播间类型；1：抖音，2：快手，3：视频号，4：淘宝
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function getUserLiveUrl()
    {
        $input = Request()->param();

        $item_id = $input['item_id'];
        $item_url = $input['item_url'];
        $item_type = $input['item_type'];

        if (empty($item_id)) apiReturn(2, '直播间id不能为空');
        if (empty($item_url)) apiReturn(2, '直播地址不能为空');
        if (empty($item_type)) apiReturn(2, '直播间类型不能为空');

        $info = Db::name('live')->where(['id' => $item_id])->find();
        if ($info) {
            $goods_copywrite_arr = json_decode($info['goods_copywrite_json'], true);
            $goods_copywrite_ids_str = '';
            if ($goods_copywrite_arr) {
                foreach ($goods_copywrite_arr as &$v) {
                    if ($v['goods_copywrite_ids']) {
                        if ($goods_copywrite_ids_str == '') {
                            $goods_copywrite_ids_str = $v['goods_copywrite_ids'];
                        } else {
                            $goods_copywrite_ids_str .= ',' . $v['goods_copywrite_ids'];
                        }
                    }
                }
            }

            $qa_list = [];
            if ($goods_copywrite_ids_str) {
                $goods_copywrite_list = Db::name('goods_copywrite')->field('id,keyword')->where(['id' => ['IN', $goods_copywrite_ids_str]])->select();
                if ($goods_copywrite_list) {
                    foreach ($goods_copywrite_list as &$v) {
                        if ($v['keyword']) {
                            $keyword_arr = explode('/', $v['keyword']);
                            foreach ($keyword_arr as $val) {
                                $qa_list[] = [
                                    'qa_id' => $v['id'],
                                    'qa_key' => $val,
                                    'qa_type' => 1
                                ];
                            }
                        }
                    }
                }
            }

            if ($interact_copywrite_ids = $info['interact_copywrite_ids']) {
                $interact_copywrite_list = Db::name('interact_copywrite')->field('id,keyword')->where(['id' => ['IN', $interact_copywrite_ids]])->select();
                if ($interact_copywrite_list) {
                    foreach ($interact_copywrite_list as &$v) {
                        if ($v['keyword']) {
                            $keyword_arr = explode('/', $v['keyword']);
                            foreach ($keyword_arr as $val) {
                                $qa_list[] = [
                                    'qa_id' => $v['id'],
                                    'qa_key' => $val,
                                    'qa_type' => 2
                                ];
                            }
                        }
                    }
                }
            }

            $param = json_encode(['itemid' => $item_id, 'url' => $item_url, 'item_type' => $item_type, 'qalist' => $qa_list], JSON_UNESCAPED_UNICODE);
            $result = httpRequest(getHost() . ':8080/start', $param);
            $result = json_decode($result, true);
            if ($result['code'] == 1) {
                apiReturn(1, '成功');
            } else {
                apiReturn(2, $result['msg']);
            }
        } else {
            apiReturn(2, '直播间不存在或已删除');
        }
    }

    /**
     * 问答入库
     * api POST /index/{controller}/{method}
     * @param int item_id   *直播间id
     * @param int qa_id   *问题文案id
     * @param int qa_type   *问题文案类型，1：商品文案，2：互动文案
     * @param int user_key   *直播间用户标识
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * */
    public function setUserLiveUrl()
    {
        $input = Request()->param();

        $item_id = $input['item_id'];
        $qa_id = $input['qa_id'];
        $qa_type = $input['qa_type'];
        $user_key = $input['user_key'];

        if (empty($item_id)) apiReturn(2, '直播间id不能为空');
        if (empty($qa_id)) apiReturn(2, '问题文案id不能为空');
        if (empty($qa_type)) apiReturn(2, '问题文案类型不能为空');
        if (empty($user_key)) apiReturn(2, '直播间用户标识不能为空');

        $data = [
            'live_id' => $item_id,
            'copywrite_id' => $qa_id,
            'copywrite_type' => $qa_type,
            'user_key' => $user_key,
            'create_time' => time()
        ];

        $res = Db::name('question')->insert($data);
        if ($res) {
            apiReturn(1, '成功');
        } else {
            apiReturn(2, '失败');
        }
    }

    /**
     * 直播间获取问答数据
     * api POST /index/{controller}/{method}
     * @param int item_id   *直播间id
     * @return int code 状态码，1：成功，2：失败
     * @return string msg 返回消息
     * @return int data.copywrite_id 文案id
     * @return int data.copywrite_type 文案类型，1：商品文案，2：互动文案
     * */
    public function getQuestionList()
    {
        $input = Request()->param();

        $live_id = $input['live_id'];

        if (empty($live_id)) apiReturn(2, '直播间id缺失');

        Db::startTrans();
        try {
            $list = Db::name('question')->field('copywrite_id,copywrite_type')->where(['live_id' => $live_id, 'is_del' => 0])->order('id asc')->select();
            if ($list) {
                Db::name('question')->where(['live_id' => $live_id, 'is_del' => 0])->setField('is_del', 1);

                apiReturn(1, '获取数据成功', $list);
            } else {
                apiReturn(2, '暂无数据');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '获取数据失败');
        }
    }

    /**
     * 查看视频进度
     */
    public function getProgress($code)
    {
        $result = (new tencentapi())->getprogress($code);
        $result = json_decode($result, true);
        if ($result['Header']['Code'] == 0) {
            $progress = $result['Payload']['Progress'];
            return $progress;
        } else {
            return -1;
        }

    }

    public function lookProgress()
    {
        $res = $this->getProgress('fe2c331e-a0e5-4657-b99a-54eb18f255e3');
        echo "<pre>";
        print_r($res);
        exit;
    }

    /**
     * 合成视频
     * */
    public function compositionVideo($live_id)
    {
        $info = Db::name('live')->where(['id' => $live_id])->find();
        if ($info) {
            $goods_copywrite_arr = json_decode($info['goods_copywrite_json'], true);
            $goods_copywrite_ids_str = '';
            $goods_copywrite_tag_ids_str = '';
            if ($goods_copywrite_arr) {
                foreach ($goods_copywrite_arr as &$v) {
                    if ($v['goods_copywrite_ids']) {
                        if ($goods_copywrite_ids_str == '') {
                            $goods_copywrite_ids_str = $v['goods_copywrite_ids'];
                        } else {
                            $goods_copywrite_ids_str .= ',' . $v['goods_copywrite_ids'];
                        }

                        if ($goods_copywrite_tag_ids_str == '') {
                            $goods_copywrite_tag_ids_str = $v['tag_id'];
                        } else {
                            $goods_copywrite_tag_ids_str .= ',' . $v['tag_id'];
                        }

                    }
                }
            }
            if ($goods_copywrite_ids_str) {
                //                $goods_copywrite_list = Db::name('goods_copywrite')->where(['id' => ['IN', $goods_copywrite_ids_str], 'video_code' => ''])->select();
                // 将商品问答文案默认生成视频，客户端不需要选择商品问答文案
                $sql = " SELECT * FROM `ai_goods_copywrite` WHERE `video_code` = '' AND `tag_id` IN (" . $goods_copywrite_tag_ids_str . ") and (`id` IN (" . $goods_copywrite_ids_str . ") || style = 2) ";
                $goods_copywrite_list = Db::name('goods_copywrite')->query($sql);
                if ($goods_copywrite_list) {
                    foreach ($goods_copywrite_list as &$v) {
                        if ($v['type'] == 1) {
                            $result = (new tencentapi())->videomakeadvanced($info['virtualman_key'], $v['content'], ['Speed' => 1], 'Text', '', getHost() . '/index/Live/compositionVideoNotify');
                        } else {
                            $result = (new tencentapi())->videomakeadvanced($info['virtualman_key'], '', ['Speed' => 1], 'OriginalVoice', $v['voice_url'], getHost() . '/index/Live/compositionVideoNotify');
                        }

                        $result = json_decode($result, true);

                        if ($result['Header']['Code'] == 0) {
                            $TaskId = $result['Payload']['TaskId'];
                            Db::name('goods_copywrite')->where(['id' => $v['id']])->setField('video_code', $TaskId);
                        }
                    }
                }
            }

            if ($interact_copywrite_ids = $info['interact_copywrite_ids']) {
                $interact_copywrite_list = Db::name('interact_copywrite')->where(['id' => ['IN', $interact_copywrite_ids], 'video_code' => ''])->select();
                if ($interact_copywrite_list) {
                    foreach ($interact_copywrite_list as &$v) {
                        if ($v['type'] == 1) {
                            $result = (new tencentapi())->videomakeadvanced($info['virtualman_key'], $v['content'], ['Speed' => 1], 'Text', '', getHost() . '/index/Live/compositionVideoNotify');
                        } else {
                            $result = (new tencentapi())->videomakeadvanced($info['virtualman_key'], '', ['Speed' => 1], 'OriginalVoice', $v['voice_url'], getHost() . '/index/Live/compositionVideoNotify');
                        }

                        $result = json_decode($result, true);

                        if ($result['Header']['Code'] == 0) {
                            $TaskId = $result['Payload']['TaskId'];
                            Db::name('interact_copywrite')->where(['id' => $v['id']])->setField('video_code', $TaskId);
                        }
                    }
                }
            }
        }
    }

    /**
     * 合成视频回调
     * */
    public function compositionVideoNotify()
    {
        $data = file_get_contents("php://input");
        file_put_contents(RUNTIME_PATH . 'input.txt', $data . PHP_EOL, FILE_APPEND);
        $result = json_decode($data, true);
        file_put_contents(RUNTIME_PATH . 'input_json.txt', json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        if ($result['Payload']['Status'] == 'SUCCESS') {
            $taskId = $result['Payload']['TaskId'];

            if ($taskId) {
                $updateData = [
                    'video_url' => $result['Payload']['MediaUrl'],
                    'video_status' => 1
                ];

                Db::name('interact_copywrite')->where(['video_code' => $taskId])->update($updateData);
                Db::name('goods_copywrite')->where(['video_code' => $taskId])->update($updateData);
            }
        } else {
            Log::error('视频生成回调 错误：' . $result['Payload']['FailMessage']);
        }
    }
}
